package zl.tools;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Comparator;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class AppendFileUtil extends JFrame{

	private static final long serialVersionUID = 1L;
	private JFileChooser jfc;
	private JTextField textField;
	private File sourceDir;
	private JButton startButton;

	public AppendFileUtil() throws Exception{
		setTitle("合并文件（安卓快播视频离线文件）");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//根据默认地址实例化文件选择器对像
		jfc = new JFileChooser(AppendFileUtil.class.getResource("").toURI().getPath());  
		//设置文件选择器对像只能选择目录
		jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);  
		JLabel label = new JLabel("视屏路径");
		textField = new JTextField(20);
		textField.setEnabled(false);
		JButton selectButton = new JButton("选择");
		selectButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if(jfc.showOpenDialog(AppendFileUtil.this) == 0)
				{
					textField.setText(jfc.getSelectedFile().toString());		
					textField.setToolTipText(jfc.getSelectedFile().toString());
					sourceDir = new File(jfc.getSelectedFile().toString());
					if(sourceDir != null){
						startButton.setText("开始合并");
						startButton.setEnabled(true);
					}
				}
			}
		});
		startButton = new JButton("开始合并");
		startButton.setEnabled(false);
		startButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent event){
				if(sourceDir == null || sourceDir.isFile()){
					return;
				}
				try {
					startAppend();
					if(System.getProperties().getProperty("os.name").startsWith("Windows")){
						Runtime.getRuntime().exec("explorer /select, " + (sourceDir.getPath()+File.separator+"result.mp4"));
					}
					startButton.setText("完成合并");
					startButton.setEnabled(false);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

		//将对像添加到窗体并设置布局方式
		JPanel temp = new JPanel();
		temp.setLayout(new FlowLayout(FlowLayout.LEFT));
		temp.add(label);
		temp.add(textField);
		temp.add(selectButton);
		getContentPane().add(temp);
		getContentPane().add(startButton,BorderLayout.SOUTH);
		pack();//窗口自定义大小
		setLocation(	//定位窗体至屏幕中央
			(int)getToolkit().getScreenSize().getWidth() / 2 - this.getWidth() / 2,
			(int)getToolkit().getScreenSize().getHeight() / 2 - this.getHeight() / 2
				);
		setResizable(false);	//设置窗体不允许修改大小
		setVisible(true);	//显示窗体
	}
	
	private void startAppend() throws Exception{
		File[] fs = sourceDir.listFiles();
		Arrays.sort(fs,this.new FileNameComparator());
		File outFilePath = new File(sourceDir.getPath()+File.separator+"result.mp4");
		OutputStream out = new FileOutputStream(outFilePath);
		InputStream in = null;
		for(File f : fs){
			if(f.isDirectory())	continue;
			System.out.println(f.getName());
			in = new FileInputStream(f);
			byte[] b = new byte[1024*1024];
			int i = 0;
			while((i = in.read(b)) != -1)
				out.write(b,0,i);
			in.close();
		}
		out.close();
	}

	
	class FileNameComparator implements Comparator<File>{

		@Override
		public int compare(File arg0, File arg1) {
			String file1Name = ((java.io.File) arg0).getName();
			int file1index = Integer.valueOf(file1Name.substring(file1Name.lastIndexOf("_")+1,file1Name.lastIndexOf(".")));
			String file2Name = ((java.io.File) arg1).getName();
			int file2index = Integer.valueOf(file2Name.substring(file2Name.lastIndexOf("_")+1,file2Name.lastIndexOf(".")));
			if(file1index > file2index)	return 1;
			else if(file1index == file2index)	return 0;
			else return -1;
		}
		
	}
	
	public static void main(String[] args) throws Exception{
		new AppendFileUtil();
	}
	/**
	 * java.awt.Desktop.getDesktop().open(new java.io.File("C:\\Program Files")); //无效
	 * 在windows系统下，可以通过命令行方式选中指定文件/文件夹，命令如下： 
		explorer /select, youFileOrFolderLocation
		
		注意：
		
		1.必须添加/select参数，否则是直接打开指定文件/文件夹，而不是选中
		
		2./select参数后面要加个逗号","（第一次发现如此奇怪的行为）
		
		那么要在java中实现在系统资源管理器中选中指定文件/文件夹，最简单的方法莫过于用Runtime类执行本地命令了：


        try {
            runtime.exec("explorer /select, " + yourFileOrFolderLocation);
        } catch (IOException e) {
            e.printStackTrace();
        }

	 */
}
